package com.example.gpssystem.service;

import com.example.gpssystem.model.Courier;
import com.example.gpssystem.model.Order;
import com.example.gpssystem.repository.LogisticsEvent;
import com.example.gpssystem.repository.mongo.CourierRepository;
import com.example.gpssystem.repository.mongo.LogisticsEventRepository;
import com.example.gpssystem.repository.mongo.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {
    private static final BigDecimal BASE_FEE = new BigDecimal("15.00");
    private static final BigDecimal PRICE_PER_KG = new BigDecimal("8.00");
    private static final BigDecimal PRICE_PER_KM = new BigDecimal("0.30");


    private BigDecimal calculateFee(Double weight, Double distance) {
        return BASE_FEE
            .add(PRICE_PER_KG.multiply(BigDecimal.valueOf(weight)))
            .add(PRICE_PER_KM.multiply(BigDecimal.valueOf(distance)));
    }

    // 添加Repository依赖注入
    private final OrderRepository orderRepository;
    private final LogisticsEventRepository logisticsEventRepository;
    @Autowired
    public OrderService(OrderRepository orderRepository, LogisticsEventRepository logisticsEventRepository) {
        this.orderRepository = orderRepository;
        this.logisticsEventRepository = logisticsEventRepository;
    }
    
    @Autowired
    private CourierRepository courierRepository;

    public void updateOrderStatus(String id, Order.OrderStatus status, String operatorId, String courierId, String currentLocation) {
        // 验证配送员活动范围
        Courier courier = courierRepository.findById(courierId)
            .orElseThrow(() -> new RuntimeException("无效的配送员ID"));
        
        if (!isInActivityRange(currentLocation, courier.getActivityRange())) {
            throw new RuntimeException("配送员超出活动范围");
        }
        
        Order order = orderRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Order not found with id: " + id));
        
        order.setStatus(status);
        orderRepository.save(order);
        
        LogisticsEvent event = new LogisticsEvent(
            id, 
            "状态变更为: " + status.name(),
            currentLocation,
            operatorId,
            courierId
        );
        event.setOrderId(id);
        event.setTimestamp(LocalDateTime.now());
        event.setDescription("状态变更为: " + status.name());
        event.setLocation("仓库中转中心");  // 需要根据实际情况获取位置
        event.setOperatorId("system");     // 需要根据登录用户获取操作员
        logisticsEventRepository.save(event);
    }

    private boolean isInActivityRange(String location, List<String> activityRange) {
        return activityRange.contains(location);
    }

    public Order getOrder(String id) {
        return orderRepository.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "订单不存在"));
    }

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    public Order createOrder(Order order) {
        // 自动分配配送员
        Courier assignedCourier = assignCourier(order.getReceiverAddress());
        order.setId(assignedCourier.getId());
        
        order.setCreateTime(LocalDateTime.now());
        order.setShippingFee(calculateFee(order.getWeight(), order.getDistance()));
        return orderRepository.save(order);
    }

    private Courier assignCourier(String address) {
        List<Courier> allCouriers = courierRepository.findAll();
        
        // 简单实现：选择第一个活动范围包含目标地址的配送员
        return allCouriers.stream()
            .filter(courier -> courier.getActivityRange().contains(address))
            .findFirst()
            .orElseThrow(() -> new RuntimeException("No available courier for address: " + address));
    }
}